package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.search.vos.SearchArticleVo;
import io.seata.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ApArticleServiceImpl  extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper contentMapper;

    @Autowired
    private ApArticleConfigMapper configMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private CacheService cacheService;


    /**
     *
     * @param dto 查询条件
     * @param type 查询类型 1.查询更多 2.查询更新
     * @return
     */
    @Override
    public ResponseResult loadArticleList(ArticleHomeDto dto, Byte type) {
        List<ApArticle> list = apArticleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(list);
    }

    /**
     * 加载文章列表
     * @param dto
     * @param type  1 加载更多   2 加载最新
     * @param firstPage  true 是首页  false 不是首页
     * @return
     */
    @Override
    public ResponseResult loadArticleList2(ArticleHomeDto dto, Byte type, boolean firstPage) {
        if (firstPage){
            String json = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(json)){
                List<HotArticleVo> voList = JSON.parseArray(json, HotArticleVo.class);
                return ResponseResult.okResult(voList);
            }
        }
        return loadArticleList(dto ,type);
    }

    /**
     * 保存或更新文章数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveOrUpdate(ArticleDto dto) {
        //1.检查参数是否为空
        if (null == dto) {
            throw  new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.拷贝数据到dto
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto , article);
        //3.判断传递过来的数据是否包含id
        if (article.getId() ==null) {
            //3.1 不包含id添加
            apArticleMapper.insert(article);
            //保存配置
            ApArticleConfig config = new ApArticleConfig(article.getId());
            configMapper.insert(config);
            //保存文章内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            contentMapper.insert(content);
        }else {
            //3.2 包含id更新
            apArticleMapper.updateById(article);

            //修改文章内容
            ApArticleContent apArticleContent = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().
                    eq(ApArticleContent::getArticleId, article.getId()));
            apArticleContent.setContent(dto.getContent());
            contentMapper.updateById(apArticleContent);
        }

        //生成静态页面

        //同步完成发送kafka发送消息
        addDocumentToEs(article,dto.getContent());

        //4.封装返回数据

            return ResponseResult.okResult(article.getId());

    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {

        //更新数据库里的数据
        ApArticle apArticle = updateArticle(mess);
        //重新计算得分
        Integer score = computeScore(apArticle);
        score = score * 3;
        //更新文章对应频道的缓存数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //更新推荐的缓存数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 更新redis 数据
     * @param apArticle
     * @param score
     * @param key
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String key) {
        String json = cacheService.get(key);
        if (StringUtils.isNotBlank(json)) {
            List<HotArticleVo> voList = JSON.parseArray(json, HotArticleVo.class);

            //需要更新的文章本来就在缓存区   -- 更新文章得分即可
            Boolean flag = Boolean.TRUE;
            for (HotArticleVo vo : voList) {
                if (vo.getId().equals(apArticle.getId())) {
                    vo.setScore(score);
                    flag = Boolean.FALSE;
                    break;
                }
            }


            if (flag) {
                //当前需要更新的文章不在缓存中
                //如果缓存没有30 直接存入
                HotArticleVo vo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, vo);
                vo.setScore(score);
                if (voList.size() < 30) {
                    voList.add(vo);
                } else {
                    //缓存数据大于30条  替换得分最低的
                    voList = voList.stream()
                            .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .collect(Collectors.toList());
                    HotArticleVo lastVo = voList.get(voList.size() - 1);
                    if (lastVo.getScore() < score) {
                        voList.remove(lastVo);
                        voList.add(vo);
                    }
                }
            }


            //把数据重新设置到redis中
            voList = voList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .collect(Collectors.toList());
            cacheService.set(key ,JSON.toJSONString(voList));
        }
    }

    /**
     * 更新数据库里的数据
     * @param mess
     * @return
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle != null){
            apArticle.setCollection((apArticle.getCollection()==null?mess.getCollect():apArticle.getCollection())+mess.getCollect());
            apArticle.setComment((apArticle.getComment()==null?mess.getComment():apArticle.getComment())+mess.getComment());
            apArticle.setLikes((apArticle.getLikes()==null?mess.getLike():apArticle.getLikes())+mess.getLike());
            apArticle.setViews((apArticle.getViews()==null?mess.getView():apArticle.getViews())+mess.getView());
            updateById(apArticle);
        }
        return apArticle;
    }

    /**
     * kafka发送消息
     * @param article
     * @param content
     */
    private void addDocumentToEs(ApArticle article, String content) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(article,vo);
        vo.setContent(content);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
